let localUserInfo = wx.getStorageSync('localUserInfo');
const DEFAULT_PAGE = 0;

Component({
    startPageX: 0,
    currentView: DEFAULT_PAGE,
    properties:{
        userId: String
    },
    data:{
        toView: `card+${DEFAULT_PAGE}`,
        cardInfo:{},
        list: [
            'birds',
            'insects',
            'plants'
        ]
    },
    touchStart(e){
        this.startPageX = e.changedTouches[0].pageX;
    },
    touchEnd(e){
        const moveX = e.changedTouches[0].pageX - this.startPageX;
        const maxPage = this.data.list.length - 1;
        if(Math.abs(moveX) >= 150) {
            if( moveX > 0) {
                this.currentView = this.currentView != 0 ? this.currentView - 1: 0;
            } else {
                this.currentView = this.currentView != maxPage ? this.currentView + 1 : maxPage;
            }
        }
        this.setData({
            toView: `card_${this.currentView}`
        });
    },
    methods:{
        getCardDetail(){
            let that=this;
            const db=wx.cloud.database();
            const _=db.command;
            db.collection("card-items")
                .where({
                    userId:this.properties.userId
                })
                .limit(1)
                .get({
                    success:function(res){
                        if(res&&res.data&&res.data.length){
                            that.setData({
                                cardInfo:res.data[0]
                            });
                            getApp().globalData.userInfo.cardInfo = that.data.cardInfo;
                            console.log(JSON.stringify(getApp().globalData.userInfo.cardInfo));
                            localUserInfo.cardInfo = that.data.cardInfo;
                            wx.setStorageSync('localUserInfo', localUserInfo);
                        }
                    },
                    fail:function(event){
                        console.error(event);
                    }
                });
        }
    },
    ready() {
        console.log(JSON.stringify(getApp().globalData.userInfo.cardInfo));
        console.log(JSON.stringify(localUserInfo));
        if(!localUserInfo.cardInfo || JSON.stringify(localUserInfo.cardInfo)=="{}"){
            this.getCardDetail();

        } else {
            this.setData({
                cardInfo: localUserInfo.cardInfo
            })
        }
        
    }
})